<?php

namespace app\user\controller;

use app\BaseController;
use app\model\CrisisLogModel;
use app\model\CrisisUserModel;
use think\App;
class Interfere extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 危机上报
     * @return bool|string
     */
    public function CrisisReporting(): bool|string
    {
        $CrisisUserModel = new CrisisUserModel();
        $CrisisUserModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'name|危机用户名称' => 'require',
                'sex|危机用户性别' => 'require',
                'department_name|危机用户部门名称' => 'require',
                'problem|危机用户问题' => 'require',
                'behavior|危机用户表现行为' => 'require',
                'informant|上报人身份' => 'require',
                'phone|联系方式' => 'require',
            ]);
            $is_disable = $CrisisUserModel->where([
                ['uid', '=', $this->userData['id']],
                ['is_disable', '>', 0]
            ])->field('is_disable,up_time')->select()->toArray();
            if (!empty($is_disable)) {
                foreach ($is_disable as $v) {
                    $day = match ($v['is_disable']) {
                        1 => 3,
                        2 => 7,
                        3 => 15,
                        4 => 30,
                    };
                    $time = $v['up_time'] + ((24 * 60 * 60) * $day);
                    if ($time > time()) throw new \Exception('恶意上报被禁用中~');
                }
            }
            //消息记录盒子
            $CrisisLogModel = new CrisisLogModel();
            $CrisisLogModel->insert([
                'unit_id' => $this->userData['unit_id'],
                'uid' => 0,
                'type' => 1,
                'source_type' => $param['informant'] == 1 ? 3 : 4,
                'behavior' => '危机上报待审核',
                'time' => time()
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            $CrisisUserModel->insert($param);
            $CrisisUserModel->commit();
            return success([], '提交成功！');
        } catch (\Exception $e) {
            $CrisisUserModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}